package com.avantis.admin.service.impl;

import com.avantis.admin.service.LikeService;
import com.avantis.common.utils.IRedisCommands;
import com.avantis.common.utils.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: tracywang
 * @Date: 2019/4/30
 * @Descrption:
 */
@Service
public class LikeServiceImpl implements LikeService {

    @Autowired
    private IRedisCommands iRedisCommands;

    @Override
    public int getLikeStatus(int userId, int entityType, int entityId) {
        //根据当前用户的userid分别生成一个likeKey 和 disLikeKey,再分别判断这两个值是否在对应的Like集合中和disLikeKey集合中
        //比如如果在likeKey集合中，就返回一个1，否则返回-1
        String likeKey = RedisKeyUtil.getLikeKey(entityId, entityType);
        //判断值为userId 的用户是否在key为listKey 的集合中
        if(iRedisCommands.sismember(likeKey, String.valueOf(userId))){
            return 1;
        }
        String disLikeKey = RedisKeyUtil.getDisLikeKey(entityId, entityType);
        return iRedisCommands.sismember(disLikeKey, String.valueOf(userId)) ? -1: 0;
    }

    @Override
    public long like(int userId, int entityType, int entityId) {
        //在当前news上点赞后获取key:   LIKE:ENTITY_NEWS:2
        String likeKey = RedisKeyUtil.getLikeKey(entityId, entityType);
        //在喜欢集合中添加当前操作用户的userId(即当前用户点赞后，被点赞用户的like集合中就会加上一个点赞的用户信息)
        iRedisCommands.sadd(likeKey, String.valueOf(userId));

        String disLikeKey = RedisKeyUtil.getDisLikeKey(entityId, entityType);
        iRedisCommands.srem(disLikeKey, String.valueOf(userId));

        //返回点赞数量
        return iRedisCommands.sCard(likeKey);
    }

    @Override
    public long disLike(int userId, int entityType, int entityId) {
        //谁点击反对，谁就出现在key为dislikeKey的Set集合中
        String disLikeKey = RedisKeyUtil.getDisLikeKey(entityId, entityType);
        iRedisCommands.sadd(disLikeKey, String.valueOf(userId));

        //从赞中删除
        String likeKey = RedisKeyUtil.getLikeKey(entityId, entityType);
        iRedisCommands.srem(likeKey, String.valueOf(userId));

        return iRedisCommands.sCard(likeKey);
    }
}
